package top.kaoshanji.p1ch02b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * author kaoshanji
 * ^_^
 * create time 2024/12/23 18:20
 */
public class SimpleProxyV2 {

    private static final Logger logger = LogManager.getLogger(SimpleProxyV2.class);

    public static void main(String[] args) {

        useGenericProxy();

    }


    public static <T> T makeProxy(Class<T> intf, final T object) {
        logger.info("...代码清单 p1ch02b-03：为任何接口及其实现类创建代理的工厂方法(2.3.1节)...");

        LoggingInvocationHandler handler = new LoggingInvocationHandler(object);
        ClassLoader cl = object.getClass().getClassLoader();
        return (T) Proxy.newProxyInstance(cl, new Class<?>[]{intf}, handler);

    }

    public static void useGenericProxy() {
        logger.info("...代码清单 p1ch02b-04：创建代理对象的工厂方法的使用示例(2.3.1节)...");

        String str = "Hello World";
        Comparable proxy = makeProxy(Comparable.class, str);
        proxy.compareTo("Good");

        List<String> list = new ArrayList<>();
        list = makeProxy(List.class, list);
        list.add("Hello");

    }


}
